<template>
  <div>
    <Row>
      <Col :span="19">
        <DatePicker
          type="month"
          v-model="params.date"
          clearable
          :transfer="true"
          @on-change="askData"
          placeholder="月份选择"
        />

        <Select
          v-model="params.project_id"
          v-width="150"
          placeholder="请选择项目"
          :transfer="true"
          @on-change="askData"
          class="ivu-ml-8"
        >
          <Option
            v-for="item in projectList"
            :value="+item.value"
            :key="item.vale"
            >{{ item.label }}</Option
          >
        </Select>
        <Select
          v-model="params.channel_id"
          v-width="150"
          placeholder="请选择渠道"
          clearable
          multiple
          :transfer="true"
          @on-change="askData"
          class="ivu-ml-8"
        >
          <Option
            v-for="item in channelList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
        <Select
          v-model="params.status"
          v-width="150"
          placeholder="对账状态"
          clearable
          :transfer="true"
          @on-change="askData"
          class="ivu-ml-8"
        >
          <Option
            v-for="item in statusList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </Col>
      <Col :span="5" class="ivu-text-right">数据更新时间：{{ updateTime }}</Col>
    </Row>
    <Table
      :columns="columns"
      :data="data"
      :loading="loading"
      class="ivu-mt-16"
      :max-height="560"
      show-summary
      :summary-method="handleSummary"
    >
      <template slot="source_name" slot-scope="{ row }">
        {{ row.source_name }}
      </template>
      <template slot="status_name" slot-scope="{ row }">
        <Tag
          type="border"
          :color="
            row.status == 2
              ? 'success'
              : row.status == 1
              ? 'primary'
              : 'default'
          "
          >{{ row.status_name }}</Tag
        >
      </template>
      <template slot="action" slot-scope="{ row }">
        <span v-if="row.status == 2">
          <a
            :disabled="true"
            v-hasC="{
              name: 'v1-marketing-dingtalk-check-bill',
              flag: 'v1/marketing/dingtalk/check-bill',
            }"
            >对账</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-marketing-dingtalk-check-bill',
              flag: 'v1/marketing/dingtalk/check-bill',
            }"
          />
          <a
            :disabled="true"
            v-hasC="{
              name: 'v1-marketing-dingtalk-end-bill',
              flag: 'v1/marketing/dingtalk/end-bill',
            }"
            >扎帐</a
          >
        </span>
        <span v-else>
          <a
            @click="handleCheck(row)"
            v-hasC="{
              name: 'v1-clue-form-update',
              flag: 'v1/clue/form/update',
            }"
            >对账</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-clue-form-update',
              flag: 'v1/clue/form/update',
            }"
          />
          <a
            @click="handleEnd(row)"
            v-hasC="{
              name: 'v1-clue-form-delete',
              flag: 'v1/clue/form/delete',
            }"
            >扎帐</a
          >
        </span>
      </template>
    </Table>

    <Page
      :total="total"
      class="ivu-mt-16"
      :current.sync="params.page"
      :page-size="params.pageSize"
      :page-size-opts="options"
      @on-change="changePage"
      show-total
      show-elevator
      show-sizer
      @on-page-size-change="changePageSize"
    />

    <Modal
      v-model="showForm"
      title="对账"
      :draggable="true"
      :mask-closable="false"
      @on-cancel="handleCancel"
      footer-hide
    >
      <Form
        :model="formItem"
        :label-width="80"
        ref="formItem"
        :rules="createRules"
      >
        <FormItem label="系统结存">
          {{ formItem.surplus_recharge_money }}
        </FormItem>
        <FormItem label="调差" prop="diff_money">
          <Input v-model="formItem.diff_money" placeholder="请输入充值金额" />
        </FormItem>
        <FormItem label="实际结存">
          {{
            parseFloat(formItem.surplus_recharge_money) +
            (parseFloat(formItem.diff_money) || 0)
          }}
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input
            v-model="formItem.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </FormItem>
      </Form>

      <div class="modalFoot">
        <Button @click="handleCancel()">取消</Button>
        <Button
          class="ivu-ml-16"
          :loading="btnLoading"
          type="primary"
          @click="handleSave()"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  dingtalkBillList,
  checkBill,
  endBill,
  billCondition,
} from "@/api/hqapi";
export default {
  name: "statementaccount",
  data() {
    return {
      updateTime: "",
      loading: false,
      btnLoading: false,
      showForm: false,
      projectList: [],
      channelList: [],
      statusList: [],
      params: {
        date: new Date(),
        project_id: "",
        channel_id: [],
        page: 1,
        pageSize: 10,
      },
      total: 0,
      options: [10, 20, 50, 100],
      columns: [
        {
          title: "项目",
          key: "project_name",
          width: 100,
        },
        {
          title: "渠道",
          slot: "source_name",
          minWidth: 120,
        },
        {
          title: "月份",
          key: "month_time_str",
          width: 100,
        },
        {
          title: "上月结存",
          key: "history_surplus_recharge_money",
          width: 120,
        },
        {
          title: "本月充值",
          key: "recharge_money",
          width: 120,
        },
        {
          title: "本月实际消费",
          key: "real_money",
          width: 120,
        },
        {
          title: "状态",
          slot: "status_name",
          width: 100,
        },
        {
          title: "本月结存",
          key: "surplus_recharge_money",
          width: 120,
        },
        {
          title: "调差",
          key: "diff_money",
          width: 100,
        },
        {
          title: "备注",
          key: "remark",
          minWidth: 120,
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 110,
        },
      ],
      data: [],
      formItem: {
        id: "",
        surplus_recharge_money: "",
        sj_surplus_recharge_money: "",
        diff_money: "",
        remark: "",
      },
      createRules: {},
    };
  },

  methods: {
    initData() {
      this.formItem = {
        id: "",
        surplus_recharge_money: "",
        sj_surplus_recharge_money: "",
        diff_money: "",
        remark: "",
      };
      this.$refs.formItem.resetFields();
    },
    changeData(data) {
      data.forEach((item) => {
        item.title = item.label;
        item.selected = false;
        if (item.children && item.children.length > 0) {
          this.changeData(item.children);
        }
      });
      return data;
    },
    changeListData(data) {
      data.forEach((item) => {
        item.real_money =
          (parseInt(item.market_money * 100) +
            parseInt(item.construct_money * 100)) /
          100;
      });
      return data;
    },
    getData(type = false) {
      this.loading = true;
      billCondition().then((resault) => {
        if (type) {
          this.projectList = resault.project_arr;
          this.channelList = this.changeData(resault.channel_arr);
          this.statusList = resault.status_arr;
          this.params.project_id = this.params.project_id
            ? this.params.project_id
            : this.projectList[0].value;
        }
        let params = {
          project_id: this.params.project_id,
          channel_id: this.params.channel_id,
          month_time: this.params.date
            ? this.$Date(this.params.date).format("YYYY-MM")
            : "",
          status: this.params.status,
          page: this.params.page,
          pageSize: this.params.pageSize,
        };
        dingtalkBillList(params)
          .then((res) => {
            this.updateTime = res.bill_updated_time;
            this.data = this.changeListData(res.list);
            this.total = res.total;
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    askData() {
      this.params.page = 1;
      this.getData();
    },
    changePage(e) {
      this.params.page = e;
      this.getData();
    },
    changePageSize(e) {
      this.params.pageSize = e;
      this.getData();
    },
    handleCheck(row) {
      this.initData();
      this.formItem = {
        id: row.id,
        surplus_recharge_money: row.surplus_recharge_money,
        sj_surplus_recharge_money:
          Number(row.diff_money) + Number(row.surplus_recharge_money),
        diff_money: row.diff_money,
        remark: row.remark,
      };
      this.showForm = true;
    },
    handleSave() {
      this.btnLoading = true;
      let params = {
        id: this.formItem.id,
        diff_money: this.formItem.diff_money,
        remark: this.formItem.remark,
      };
      checkBill(params)
        .then(() => {
          this.$Message.success("对账成功!");
          this.btnLoading = false;
          this.showForm = false;
          this.getData();
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    handleEnd(row) {
      this.$Modal.confirm({
        title: "扎帐",
        content: "扎账后当月已关联的数据不要修改，是否确认扎帐？",
        loading: true,
        onOk: () => {
          endBill({ id: row.id })
            .then(() => {
              this.getData();
              this.$Modal.remove();
            })
            .catch(() => {
              this.$Modal.remove();
            });
        },
      });
    },
    handleSummary({ columns, data }) {
      const checkArr = [
        "history_surplus_recharge_money",
        "market_money",
        "recharge_money",
        "surplus_recharge_money",
        "diff_money",
        "construct_money",
        "real_money",
      ];
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: "合计",
          };
          return;
        } else if (checkArr.includes(key)) {
          const values = data.map((item) => Number(item[key]));
          if (!values.every((value) => isNaN(value))) {
            const v = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return Number(prev) + Number(curr);
              } else {
                return prev;
              }
            }, 0);
            sums[key] = {
              key,
              value: v.toFixed(2),
            };
          } else {
            sums[key] = {
              key,
              value: "",
            };
          }
        } else {
          sums[key] = {
            key,
            value: "",
          };
          return;
        }
      });

      return sums;
    },
    handleCancel() {
      this.showForm = false;
    },
  },
};
</script>
<style lang="less" scoped>
.modalFoot {
  text-align: right;
  border-top: 1px solid #ddd;
  padding-top: 16px;
  margin-top: 24px;
}
</style>
<style>
.date-picker--box,
.date-picker--table {
  width: auto !important;
  height: auto;
}
.date-picker--popper-arrow:before {
  position: relative;
}
.date-picker--popper-dialog {
  z-index: 9999;
}
</style>
